<template>
  <div>
    <!--头部行表单 ：搜索 增加 导出 -->
    <div class="filter-container">
      <el-input v-model="query.keyword" placeholder="搜索用户" style="width: 200px;" class="filter-item" @keyup.enter.native="handleSearch" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
<!--      <el-button disabled class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleAdd">增加</el-button> -->
      <el-button :loading="exportLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">导出</el-button>
    </div>

    <!-- 数据列表 编辑 删除 -->
    <div class="list-container">
      <el-table :data="dataList" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
        <el-table-column label="ID" prop="id" width="60" sortable="custom" align="center"></el-table-column>
        <el-table-column label="用户名" prop="name" sortable="custom"></el-table-column>
        <el-table-column label="电话" prop="phone" sortable="custom"></el-table-column>
        <el-table-column label="性别" prop="gender" width="60" align="center">
          <template slot-scope="{ row }">
            {{ row.gender == 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="头像" prop="avatar">
          <template slot-scope="{ row }">
            <el-avatar size="small" :src="BaseAPI + row.avatar"></el-avatar>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row.id)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.$index,scope.row.id)">删除</el-button>
            <el-button type="text" icon="el-icon-refresh-left" @click="handleResetPassWord(scope.row.id)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="recordTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <user-edit v-if="editDialogVisible" ref="editDialog" @refreshDataList="loadDataList"></user-edit>
  </div>
</template>

<script>
import * as UserAPI from '@/api/user.js';
import UserEdit from './components/UserEdit.vue';
export default {
  name: 'userList',
  components: {
    UserEdit  //注册组件
  },
  data() {
    return {
      dataList: [], //列表数据
      query: {
        keyword: '', //搜索关键字
        pageIndex: 1, //页号
        pageSize: 10, //页大小
        orderBy: 'id' //排序字段
      },
      recordTotal: 0, //记录总数
      exportLoading: false, //导出
      editDialogVisible: false, //编辑框是否显示
    };
  },
  created() {
    this.loadDataList(); // 初始列表数据
  },

  methods: {
    // 获取列表数据
    loadDataList() {
      UserAPI.getUserList(this.query).then(result => {
        this.dataList = result.data;
        this.recordTotal = result.recordTotal;
      });
    },

    // 触发搜索按钮
    handleSearch() {
      this.query.pageIndex = 1;
      this.loadDataList();
    },

    // 触发增加按钮
    // handleAdd() {
    //   this.$message.warning("管理员是不能增加注册用户的");
    // },

    // 触发导出按钮
    async handleExport() {
      // this.$message("导出，待完成...")
      this.exportLoading = true;
      let EXCEL = await import('@/vendor/Export2Excel');
      const headers = {
        用户Id: 'id',
        用户名: 'name',
        性别: 'gender',
        手机号: 'phone',
      };

      try {
        const params = {
          pageIndex: 1,
          pageSize: this.recordTotal
        };
        const result = await UserAPI.getUserList(params);
        const userList = result.data;
        const data = this.formatJson(headers, userList);
        EXCEL.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '注册用户数据'
        });
        this.exportLoading = false;
        this.$message.success('导出成功');
      } catch (err) {
        this.exportLoading = false;
        console.log(err);
      }
    },

    // 将json数据转换成导出excel参数所需要的数组中包数组的格式
    formatJson(headers, list) {
      return list.map(item => {
        // 先找到每条员工数据
        return Object.keys(headers).map(key => {
          // 找到每个中文表头key，则headers[key]就是中文表头对应的英文
          if (headers[key] === 'gender') {
            // 转换格式
            return item[headers[key]] === 1 ? '男' : '女';
          }
          return item[headers[key]];
        });
      });
    },

    // 触发字段排序
    sortChange({ prop, order }) {
      if (order === 'ascending') {
        this.query.orderBy = `${prop} ASC`;
      } else {
        this.query.orderBy = `${prop} DESC`;
      }
      this.handleSearch();
    },

    // 删除操作
    handleDelete(index,id) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 选择了确认，则删除后端数据库中的记录
          UserAPI.deleteUserById(id)
            .then(() => {
              this.dataList.splice(index, 1); //同步列表中的记录
              this.$message.success('删除成功');
            })
            .catch(() => {});
        })
        .catch(() => {});
    },

    // 编辑操作，id为编辑记录的ID
    handleUpdate(id) {
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editDialog.init(id);
      });
    },

    // 密码重置操作
    handleResetPassWord(id) {
      // 二次确认
      this.$confirm('确定要重置密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 选择了确认，则删除后端数据库中的记录
          let password = '123456'; //统一的重置密码
          UserAPI.resetUserPasswordById(id, password)
            .then(() => {
              this.$message.success('用户密码重置成功！');
            })
            .catch(() => {});
        })
        .catch(() => {});
    },

    // 分页导航=======================================
    handlePageChange(val) {
      this.query.pageIndex = val;
      this.loadDataList();
    }
  }
};
</script>

<style scoped>
</style>
